package Dao;

import Bean.User;
import Utils.DBHelp;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.Year;
import java.util.List;

public class BasicDao<T> {
    //查询单个语句
    public T selectOne(String sql,Class<T> tClass,Object... parameters){
        T query = null;
        Connection connection = DBHelp.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        try {
             query = queryRunner.query(connection, sql, new BeanHandler<>(tClass), parameters);
             return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public boolean dml(String sql,Object... parameters){
        Connection connection = DBHelp.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(connection,sql,parameters);
        } catch (SQLException e) {
           return false;
        }
        return true;
    }
    public List<T> queryMulti(String sql,Class<T> tClass){
        Connection connection = DBHelp.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        try {
            return queryRunner.query(connection, sql, new BeanListHandler<>(tClass));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public List<T> getSomeQuery(String sql,Class<T> tClass,Object... nums){
        Connection connection = DBHelp.getConnection();
        QueryRunner queryRunner = new QueryRunner();
        try {
            return queryRunner.query(connection, sql, new BeanListHandler<>(tClass),nums);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public Integer getCount(String sql,Object... nums){
        QueryRunner queryRunner = new QueryRunner();
        Integer index = 0;
        try {
            Long update = (Long)queryRunner.query(DBHelp.getConnection(), sql,new ScalarHandler(),nums);
            index = update.intValue();
        } catch (SQLException e) {
            index = -1;
        }
        return index;
    }

}
